<?php
namespace Api\Controller;
use Think\Controller;
define("TOKEN", "zltc");
/*
 * 小程序客服流程
 * 1.用户发送消息至微信服务器，微信服务器并转发至我们服务器
 * 2.调用接收消息方法，处理用户发送过来的消息，并发送给商家或者某人
 * 3.客服回复消息，调用发送消息接口。发送至用户
 *
 */



class KefuController extends Controller {

    public function check_sever(){     //校验服务器地址URL
        if (isset($_GET['echostr'])) {
            $this->valid();
        }else{
            $this->responseMsg();
        }
    }

    public function valid()  //第一次验证服务器用
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            header('content-type:text');
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {

        $postStr = file_get_contents('php://input');   //此处推荐使用file_get_contents('php://input')获取后台post过来的数据

        if (!empty($postStr) && is_string($postStr)){
            $postArr = json_decode($postStr,true);
            if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){   //用户发送文本消息
                //查出商户店铺店主
                $a = "session=".session('shop_id')."/content=".$postArr['Content'].'/json='.json_encode($postArr);
                file_put_contents('tjson.txt',$a,FILE_APPEND);
                $shop = M('shop')->where(['shop_id'=>session('shop_id')])->find();
                //$fromUsername = $postArr['FromUserName'];   //发送者openid
                $data=array(
                    "touser"=>$shop['openid'],
                    "msgtype"=>"text",
                    "text"=>array("content"=>$postArr['Content'])
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //PHP版本5.4以上
                $this->post2($json,2);
            }else if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){ //用户发送图文消息
                $fromUsername = $postArr['FromUserName'];   //发送者openid
                $media_id = '';   //输入想要回复的图片消息的media_id
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"image",
                    "image"=>array("media_id"=>$media_id)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);
                $this->post2($json,2);
            }else if($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){ //用户进入客服

                //用户第一次进入，保留传过来的shop_id
                $shop_id = $postArr['SessionFrom'];
                session('shop_id',$shop_id);
                $fromUsername = $postArr['FromUserName'];   //用户第一次进入客服系统
                //file_put_contents('tjson.txt',$fromUsername,FILE_APPEND);
                $member = M('member')->where(['openid'=>$fromUsername])->find();
                /*$a = M()->getLastSql();*/
                file_put_contents('shop.txt',$postArr['SessionFrom'],FILE_APPEND);

                $content = '欢迎'.$member['nickname'];



                $data=array(
                    "touser"=>$member['openid'],
                    "msgtype"=>"text",
                    "text"=>array("content"=>$content)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);

                $this->post2($json,$member['wid']);
            }else{
                exit('error');
            }
        }else{
            exit;
        }
    }


    //向客户端发送回复消息
    public function post2($data,$wid ){

        $access_token = $this->get_access_token_mp($wid);
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: text',
                'content' => $data
            )
        );

//        $json = json_encode($opts, JSON_UNESCAPED_UNICODE);
//        $res = $this->ihttp_post($url, $json);
//        $td = json_decode($res, true);
            file_put_contents('123.txt',$data);

        $context = stream_context_create($opts);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    //获取微信公众平台token
    public function get_access_token_mp($wid)
    {

        $wechat = M('wechat')->where(array('wid'=>$wid))->find();
        $token = S("access_token_mp");
        if($token){
            return $token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wechat['appid']}&secret={$wechat['app_secret']}";
        $res = $this->ihttp_get($url);
        $td = json_decode($res, true);
        if($td['access_token']){
            S("access_token_mp", $td['access_token'], $td['expires_in'] - 120);
            return $td['access_token'];
        }else{
            return false;
        }
    }

    protected function ihttp_post($url, $post_data){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    protected function ihttp_get($url){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

}